<template>
  <div ref="echarts"></div>
</template>

<script>
import * as echarts from "echarts";
export default {
  name: "Echarts",
  props: {
    chartType: {
      type: String,
      required: true,
    },
    chartData: {
      type: Object,
      default() {
        return {
          xData: [],
          series:[]
        };
      },
    },
  },
  data() {
    return {
        echart:null,
        options:null,
    // 折线图 柱状图
      defaultOption: {
        legend: {
          // 图例文字颜色
          textStyle: {
            color: "#333",
          },
        },
        grid: {
          left: "20%",
        },
        // 提示框
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category", // 类目轴
          data: [],
          axisLine: {
            lineStyle: {
              color: "#17b3a3",
            },
          },
          axisLabel: {
            interval: 0,
            color: "#333",
          },
        },
        yAxis: [
          {
            type: "value",
            axisLine: {
              lineStyle: {
                color: "#17b3a3",
              },
            },
          },
        ],
        color: [
          "#2ec7c9",
          "#b6a2de",
          "#5ab1ef",
          "#ffb980",
          "#d87a80",
          "#8d98b3",
        ],
        series: [],
      },
    //   饼状图
      pieOption: {
        tooltip: {
          trigger: "item",
        },
        color: [
          "#0f78f4",
          "#dd536b",
          "#9462e5",
          "#a6a6a6",
          "#e1bb22",
          "#39c362",
          "#3ed1cf",
        ],
        series: [],
      },
    };
  },
  watch: {
      chartData:{
          handler(){
              this.initChart()
          },
          deep:true
      }
  },
  methods: {
      initChart(){
          this.initChartData()
        //   如果echart已经渲染过直接修改options，首次渲染则进行赋值和界面绘制
          if(this.echart){
              this.echart.setOption(this.options)
          }else{
              this.echart = echarts.init(this.$refs.echarts)
              this.echart.setOption(this.options)
          }
      },
      initChartData(){
          if(['line','bar'].includes(this.chartType)){
              this.defaultOption.xAxis.data = this.chartData.xData
              this.defaultOption.series = this.chartData.series
              this.options = this.defaultOption
          }else{
              this.pieOption.series = this.chartData.series
              this.options = this.pieOption

          }

      }
  }
};
</script>

<style></style>
